<template>
  <div class="app-container">
    <!-- 订单基本信息 -->
    <el-card class="order-info-card" header="订单信息" style="margin-bottom: 20px;">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="订单编号">{{ orderInfo.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <dict-tag :options="pond_order_status" :value="orderInfo.orderStatus"/>
        </el-descriptions-item>
        <el-descriptions-item label="订单类型">
          <dict-tag :options="pond_order_type" :value="orderInfo.orderType"/>
        </el-descriptions-item>
        <el-descriptions-item label="用户姓名">{{ orderInfo.userName }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ orderInfo.userPhone }}</el-descriptions-item>
        <el-descriptions-item label="鱼塘钓位">{{ orderInfo.pondName }} - {{ orderInfo.seatName }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ parseTime(orderInfo.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ orderInfo.endTime ? parseTime(orderInfo.endTime, '{y}-{m}-{d} {h}:{i}:{s}') : '进行中' }}</el-descriptions-item>
        <el-descriptions-item label="总金额">¥{{ orderInfo.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="已支付">¥{{ orderInfo.paidAmount }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(orderInfo.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ orderInfo.remark || '无' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 消费记录 -->
    <el-card class="consumption-card" header="消费记录">
      <div class="consumption-toolbar" style="margin-bottom: 20px;">
        <el-button type="primary" icon="Plus" @click="showAddConsumption" v-hasPermi="['pond:consumption:add']">添加消费</el-button>
        <el-button type="success" icon="Money" @click="showFishReturn" v-hasPermi="['pond:consumption:add']">回鱼记录</el-button>
        <el-button 
          v-if="orderInfo.orderStatus === 1" 
          type="warning" 
          icon="Check" 
          @click="handleSettle"
          v-hasPermi="['pond:order:settle']"
        >结算订单</el-button>
        <el-button type="info" icon="Back" @click="goBack">返回列表</el-button>
      </div>
      
      <el-table :data="consumptions" style="width: 100%">
        <el-table-column prop="itemName" label="消费项目" width="150" />
        <el-table-column prop="consumptionType" label="类型" width="100">
          <template #default="scope">
            <dict-tag :options="pond_consumption_type" :value="scope.row.consumptionType"/>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="80" />
        <el-table-column prop="unitPrice" label="单价" width="100">
          <template #default="scope">
            ¥{{ scope.row.unitPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="100">
          <template #default="scope">
            ¥{{ scope.row.amount }}
          </template>
        </el-table-column>
        <el-table-column prop="fishWeight" label="鱼重量(kg)" width="100">
          <template #default="scope">
            {{ scope.row.fishWeight || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="时间" width="150">
          <template #default="scope">
            {{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button 
              link 
              type="danger" 
              size="small" 
              @click="handleDeleteConsumption(scope.row)"
              v-hasPermi="['pond:consumption:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="consumption-summary" style="margin-top: 20px; text-align: right;">
        <el-tag type="success" size="large">消费总计：¥{{ orderInfo.totalAmount }}</el-tag>
      </div>
    </el-card>

    <!-- 添加消费记录对话框 -->
    <el-dialog title="添加消费记录" v-model="consumptionOpen" width="500px" append-to-body>
      <el-form ref="consumptionRef" :model="consumptionForm" :rules="consumptionRules" label-width="100px">
        <el-form-item label="消费类型" prop="consumptionType">
          <el-select v-model="consumptionForm.consumptionType" placeholder="请选择消费类型">
            <el-option
              v-for="dict in pond_consumption_type.filter(item => item.value != '3')"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="消费项目" prop="itemName">
          <el-input v-model="consumptionForm.itemName" placeholder="请输入消费项目名称" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="consumptionForm.quantity" :min="0.001" :precision="3" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input-number v-model="consumptionForm.unitPrice" :min="0.01" :precision="2" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number v-model="consumptionForm.amount" :min="0.01" :precision="2" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="consumptionForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitConsumption">确 定</el-button>
          <el-button @click="consumptionOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 回鱼记录对话框 -->
    <el-dialog title="回鱼记录" v-model="fishReturnOpen" width="500px" append-to-body>
      <el-form ref="fishReturnRef" :model="fishReturnForm" :rules="fishReturnRules" label-width="100px">
        <el-form-item label="鱼种" prop="fishTypeId">
          <el-select v-model="fishReturnForm.fishTypeId" placeholder="请选择鱼种">
            <el-option
              v-for="fishType in fishTypes"
              :key="fishType.id"
              :label="fishType.name"
              :value="fishType.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="鱼重量(kg)" prop="fishWeight">
          <el-input-number v-model="fishReturnForm.fishWeight" :min="0.001" :precision="3" placeholder="请输入鱼重量" />
        </el-form-item>
        <el-form-item label="单价(元/kg)" prop="unitPrice">
          <el-input-number v-model="fishReturnForm.unitPrice" :min="0.01" :precision="2" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number v-model="fishReturnForm.amount" :min="0.01" :precision="2" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="fishReturnForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFishReturn">确 定</el-button>
          <el-button @click="fishReturnOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 结算订单对话框 -->
    <el-dialog title="结算订单" v-model="settleOpen" width="500px" append-to-body>
      <el-form ref="settleRef" :model="settleForm" :rules="settleRules" label-width="80px">
        <el-form-item label="订单编号">
          <span>{{ settleForm.orderNo }}</span>
        </el-form-item>
        <el-form-item label="用户信息">
          <span>{{ settleForm.userName }} ({{ settleForm.userPhone }})</span>
        </el-form-item>
        <el-form-item label="总金额">
          <span>¥{{ settleForm.totalAmount }}</span>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker 
            v-model="settleForm.endTime" 
            type="datetime" 
            placeholder="选择结束时间" 
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="settleForm.remark" type="textarea" placeholder="请输入结算备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSettle">确认结算</el-button>
          <el-button @click="settleOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="OrderDetail">
import { getOrder, settleOrder } from "@/api/pond/order";
import { getConsumptionsByOrderId, addConsumptionRecord, addFishReturn, delSingleConsumption } from "@/api/pond/consumption";

const { proxy } = getCurrentInstance();
const { pond_order_status, pond_order_type, pond_consumption_type } = proxy.useDict('pond_order_status', 'pond_order_type', 'pond_consumption_type');
const route = useRoute();
const router = useRouter();

const orderInfo = ref({});
const consumptions = ref([]);
const consumptionOpen = ref(false);
const fishReturnOpen = ref(false);
const settleOpen = ref(false);
const fishTypes = ref([]);

const data = reactive({
  consumptionForm: {
    orderId: null,
    consumptionType: null,
    itemName: null,
    quantity: 1,
    unitPrice: null,
    amount: null,
    remark: null
  },
  fishReturnForm: {
    orderId: null,
    fishTypeId: null,
    fishWeight: null,
    unitPrice: null,
    amount: null,
    remark: null
  },
  settleForm: {
    orderId: null,
    orderNo: null,
    userName: null,
    userPhone: null,
    totalAmount: null,
    endTime: null,
    remark: null
  },
  consumptionRules: {
    consumptionType: [{ required: true, message: "消费类型不能为空", trigger: "change" }],
    itemName: [{ required: true, message: "消费项目不能为空", trigger: "blur" }],
    quantity: [{ required: true, message: "数量不能为空", trigger: "blur" }],
    unitPrice: [{ required: true, message: "单价不能为空", trigger: "blur" }],
    amount: [{ required: true, message: "金额不能为空", trigger: "blur" }]
  },
  fishReturnRules: {
    fishTypeId: [{ required: true, message: "鱼种不能为空", trigger: "change" }],
    fishWeight: [{ required: true, message: "鱼重量不能为空", trigger: "blur" }],
    unitPrice: [{ required: true, message: "单价不能为空", trigger: "blur" }],
    amount: [{ required: true, message: "金额不能为空", trigger: "blur" }]
  },
  settleRules: {
    endTime: [{ required: true, message: "结束时间不能为空", trigger: "change" }]
  }
});

const { consumptionForm, fishReturnForm, settleForm, consumptionRules, fishReturnRules, settleRules } = toRefs(data);

/** 获取订单详情 */
function getOrderDetail() {
  const orderId = route.query.orderId;
  if (!orderId) {
    proxy.$modal.msgError("订单ID不能为空");
    return;
  }
  
  getOrder(orderId).then(response => {
    orderInfo.value = response.data;
    consumptions.value = response.data.consumptions || [];
  });
}

/** 显示添加消费对话框 */
function showAddConsumption() {
  consumptionForm.value = {
    orderId: orderInfo.value.orderId,
    consumptionType: null,
    itemName: null,
    quantity: 1,
    unitPrice: null,
    amount: null,
    remark: null
  };
  consumptionOpen.value = true;
}

/** 显示回鱼记录对话框 */
function showFishReturn() {
  fishReturnForm.value = {
    orderId: orderInfo.value.orderId,
    fishTypeId: null,
    fishWeight: null,
    unitPrice: null,
    amount: null,
    remark: null
  };
  fishReturnOpen.value = true;
}

/** 提交消费记录 */
function submitConsumption() {
  proxy.$refs["consumptionRef"].validate(valid => {
    if (valid) {
      addConsumptionRecord(consumptionForm.value).then(response => {
        proxy.$modal.msgSuccess("添加成功");
        consumptionOpen.value = false;
        getOrderDetail();
      });
    }
  });
}

/** 提交回鱼记录 */
function submitFishReturn() {
  proxy.$refs["fishReturnRef"].validate(valid => {
    if (valid) {
      addFishReturn(fishReturnForm.value).then(response => {
        proxy.$modal.msgSuccess("添加成功");
        fishReturnOpen.value = false;
        getOrderDetail();
      });
    }
  });
}

/** 删除消费记录 */
function handleDeleteConsumption(row) {
  proxy.$modal.confirm('是否确认删除该消费记录？').then(function() {
    return delSingleConsumption(row.consumptionId);
  }).then(() => {
    getOrderDetail();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 结算订单 */
function handleSettle() {
  settleForm.value = {
    orderId: orderInfo.value.orderId,
    orderNo: orderInfo.value.orderNo,
    userName: orderInfo.value.userName,
    userPhone: orderInfo.value.userPhone,
    totalAmount: orderInfo.value.totalAmount,
    endTime: null,
    remark: null
  };
  settleOpen.value = true;
}

/** 提交结算 */
function submitSettle() {
  proxy.$refs["settleRef"].validate(valid => {
    if (valid) {
      settleOrder(settleForm.value).then(response => {
        proxy.$modal.msgSuccess("结算成功");
        settleOpen.value = false;
        getOrderDetail();
      });
    }
  });
}

/** 返回列表 */
function goBack() {
  router.push('/fish/order');
}

/** 监听数量和单价变化，自动计算金额 */
watch([() => consumptionForm.value.quantity, () => consumptionForm.value.unitPrice], () => {
  if (consumptionForm.value.quantity && consumptionForm.value.unitPrice) {
    consumptionForm.value.amount = (consumptionForm.value.quantity * consumptionForm.value.unitPrice).toFixed(2);
  }
});

watch([() => fishReturnForm.value.fishWeight, () => fishReturnForm.value.unitPrice], () => {
  if (fishReturnForm.value.fishWeight && fishReturnForm.value.unitPrice) {
    fishReturnForm.value.amount = (fishReturnForm.value.fishWeight * fishReturnForm.value.unitPrice).toFixed(2);
  }
});

onMounted(() => {
  getOrderDetail();
  // 获取鱼种列表
  // getFishTypes().then(response => {
  //   fishTypes.value = response.data;
  // });
});
</script>

<style scoped>
.order-info-card {
  margin-bottom: 20px;
}

.consumption-toolbar {
  margin-bottom: 20px;
}

.consumption-summary {
  margin-top: 20px;
  text-align: right;
}
</style>